// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  // 店家卡列表
  async cardlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;

    const shopid = this.shop_userinfo.departmentid;

    const list = await this.model('or_shop_card').where({shopid: shopid, isdisabled: zt, 'name|number': ['like', '%' + search + '%']})
      .page(pages, limits)
      .order('no')
      .countSelect();

    return this.json(list);
  }

  // 开卡订单列表
  async opencardlistAction() {
    const page = JSON.parse(this.post('page'));
    const where = {
      's.departmentid': this.shop_userinfo.departmentid,
      's.ordertype': 1,
      'g.name|g.phone|g.vipcard|a.name|s.order_sn': ['like', '%' + page.search + '%']
    };
    if (page.zt != 0) {
      where['s.status'] = page.zt - 1;
    }
    // 设置时间
    if (page.times && (page.times[0] != null && page.times[1] != null)) {
      const begintime = Math.floor(new Date(page.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(page.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400;
      where['s.addtime'] = {'>=': begintime, '<': endtime};
 		}

    const data = await this.model('or_shop_order')
      .alias('s')
      .field('s.id, d.name as shopname, s.order_sn, s.recemoney, s.usebalance, s.usegiftbalance, s.status, s.addtime, IF(s.remarks!="",s.remarks,"无") as remarks, g.id as gid, g.name as gname,g.phone as gphone,g.vipcard,a.name as aname,z.name as zname')
      .join('think_or_guest g on s.guestid = g.id')
      .join('`think_or_department` d on g.departmentid = d.id')
      .join('think_or_admin a on s.operatorid = a.id')
      .join('think_or_admin z on s.auditorid = z.id')
      .page(page.pages, page.limits)
      .order('id DESC')
      .where(where)
      .countSelect();
    return this.json(data);
  }

  // 开卡操作
  async opencardAction() {
    /*
		* 只开卡，不结账
		* 如果可以开多张卡，则把赠送的品项绑定到当前订单ID上（如果退卡则通过当前订单ID调出赠送的品项）
		* 写入表[or_shop_order、or_shop_orderinfo]两张表
		* 不结账可以直接删除当前订单，也可以编辑当前订单。
		*/
    const data = JSON.parse(this.post('data'));

    // 判断客户期初是否审核未审核不能开卡
    const isinitial = await this.model('or_guest').where({id: data.ginfo.id}).getField('initial_info', true);
    if (isinitial == 0) {
      return this.fail('该客户期初未审核不能开单！');
    }
    let ginfo = data.ginfo, cards = data.cards;
    const shopid = this.shop_userinfo.departmentid;
    const addtime = Math.round(new Date().valueOf() / 1000);
    const ordersn = await this.getordersn('KKD', 1);
    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        const addorder = {
          order_sn: ordersn,
          guestid: ginfo.id,
          departmentid: shopid,
          recemoney: data.order.usemoney,
          cardreduce: 0,
          usebalance: data.order.usebalance,
          usegiftbalance: data.order.usegiftbalance,
          operatorid: this.shop_userinfo.id,
          status: 0,
          addtime: addtime,
          ordertype: 1,
          remarks: data.order.remarks,
          iscross: data.order.crossShop
        };
        const orderid = await model.add(addorder);
        if (!orderid) {
          await model.rollback();
          return this.fail('开卡失败');
        }
        // 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
        const resguest = await this.model('or_guest').db(model.db()).where({id: ginfo.id}).update({remarks: ginfo.remarks});

        const addorderinfo = [];
        for (var i = 0, cardlen = cards.length; i < cardlen; i++) {
          addorderinfo.push({
            departmentid: shopid,
            orderid: orderid,
            consumetype: 1,
            type: cards[i].rowtype,
            typeid: cards[i].id,
            typename: cards[i].name,
            num: cards[i].num,
            price: cards[i].price,
            totalprice: cards[i].num * cards[i].price,
            discount: cards[i].discount,
            amount: cards[i].amount,
            usemoney: cards[i].usemoney,
            usebalance: cards[i].usebalance,
            usegiftbalance: cards[i].usegiftbalance,
            usecard: 0,
            isgift: cards[i].isgift ? 1 : 0,
            istemp: cards[i].rowtype == 1 ? 1 : 0,
            brandid: cards[i].brandid ? cards[i].brandid : 0,
            cost: cards[i].cost
          });
        }

        const addoinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorderinfo);

        if (addoinfo) {
          await model.commit();
          return this.success({info: '开卡成功', id: orderid});
        } else {
          await model.rollback();
          return this.fail('开卡失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('操作失败！');
      }
    });
  }

  async getkaikadaninfoAction() {
    const id = this.get('id');
    const order = await this.model('or_shop_order').where({id: id}).find();
    const ginfo = await this.model('or_guest')
      .alias('g')
      .field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
      .join('left join `think_or_guest_vipgrade` v on g.level = v.id')
      .where({'g.id': order.guestid})
      .find();
    const orderlist = await this.model('or_shop_orderinfo')
      .alias('o')
      .field('o.*, c.category as cardtype, c.validity')
      .join('left join `think_or_shop_card` c on o.typeid = c.id and o.type = 3')
      .where({'o.orderid': id})
      .select();

    // 结账信息
    const accountlist = await this.model('or_shop_accountlog')
      .alias('l')
      .field('a.*, l.money as paymoney, l.accountid')
      .join('left join `think_or_shop_account` a on l.accountid = a.id')
      .where({'l.orderid': id, 'l.ordertype': 'KKD'})
      .select();

    const yejilist = await this.model('or_shop_yejiticheng')
      .alias('y')
      .field('y.*,u.name')
      .join('left join `think_or_app_user` u on y.userid = u.id')
      .where({'y.ordertype': 'KKD', 'y.orderid': id, 'addtype': 0})
      .select();

    const data = {
      order: order,
      orderlist: orderlist,
      ginfo: ginfo,
      accountlist: accountlist,
      yejilist: yejilist
    };
    return this.json(data);
  }

  // 开卡结账功能
  async opencardjiezhangAction() {
    // 开卡结账操作开始
    const data = JSON.parse(this.post('data'));

    // 取出订单信息和list
    const order = await this.model('or_shop_order').where({id: data.order.id}).find();
    if (order.status > 0) {
      return this.fail('当前订单已结账！');
    }

    const orderlist = await this.model('or_shop_orderinfo').where({orderid: data.order.id}).select();

    const orderid = data.order.id;
    let shopid = this.shop_userinfo.departmentid, addtime = order.addtime;
    // 结账事务开始
    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        /*
				* 1、首先取出order订单信息
				* 2、获取orderinfo信息（开的哪些卡和赠送的哪些品项）
				* 3、根据cardid把机构的卡项添加到客户的卡项表里（注：机构卡拉取次数要自增）
				* 4、根据cardid把机构的品项取出并添加到客户的卡项表里
				* 5、把赠送的品项添加到客户的暂存仓库里
				* 6、店家账户收款金额更新，并记录收款日志表
				* 7、如果有消耗业绩或现金业绩，则把对应的业绩分配写到对应的表里
				* 8、更新客户表信息
				* 	-> 根据客户余额消费减去相应的余额，
				*		-> 把消费信息记录到客户消费金额流量表里，
				*		-> 并且更新顾客最后到店时间
				* 9、订单信息处理后重新更新当前订单信息（主要是订单的现金消费和余额消费等）
				*/

        // 先做订单审核操作
        const resorder = await model.where({id: orderid}).update({
          status: 1,
          auditorid: this.shop_userinfo.id
        });

        let cardsubjectdata = [], goodsdata = [], goodsdatalog = [], zancundata = [];
        let rescardsubject = 1, resgoods = 1, resgoodslog = 1, reszancun = 1;
        // 接着循环订单详细表进行操作
        for (var i = orderlist.length - 1; i >= 0; i--) {
          // 如果是卡，取出卡信息写入客户卡表和卡项表
          if (orderlist[i].type == 3) {
            // 取出原生卡项
            const card = await this.model('or_shop_card')
              .alias('c')
              .db(model.db())
              .join('left join `think_or_shop_cardsubject` s on c.id = s.cardid')
              .where({'c.id': orderlist[i].typeid})
              .select();
            // 推送项目
            for (var k = card.length - 1; k >= 0; k--) {
              // 期卡暂时卡耗业绩社为零
              // 判断是否有成本扣除
              const cost = orderlist[i].cost > 0 ? orderlist[i].cost : 0;
              const amount = card[k].category == 1 ? 0 : card[k].disprice * orderlist[i].discount * card[k].num * (1 - cost / 100);
              const discount = card[k].category == 1 ? 0 : amount / (card[k].price * card[k].num);
              cardsubjectdata.push({
                guestid: order.guestid,
                subjectid: card[k].subjectid,
                num: card[k].num,
                nownum: card[k].num,
                price: card[k].price,
                discount: discount,
                disprice: card[k].price * discount,
                amount: amount,
                cardtype: card[k].category,
                orderid: orderid,
                addtime: addtime,
                endtime: card[k].category == 1 ? addtime + card[k].validity * 86400 : 0,
                shopid: this.shop_userinfo.departmentid,
                cardid: orderlist[i].typeid,
                isdisabled: 0
              });
            }
          }
          // 如果是项目，同样写入卡项表
          if (orderlist[i].type == 2) {
            const cost = orderlist[i].cost > 0 ? orderlist[i].cost : 0;
            const amount = orderlist[i].amount * (1 - cost / 100);
            const disprice = amount / orderlist[i].num;
            cardsubjectdata.push({
              guestid: order.guestid,
              subjectid: orderlist[i].typeid,
              num: orderlist[i].num,
              nownum: orderlist[i].num,
              price: orderlist[i].price,
              discount: disprice / orderlist[i].price,
              disprice: disprice,
              amount: amount,
              cardtype: 2,
              orderid: orderid,
              addtime: addtime,
              endtime: 0,
              shopid: this.shop_userinfo.departmentid,
              cardid: 0,
              isdisabled: 0
            });
          }
          // 如果是产品减库存，写库存日志，如果有暂存写暂存
          if (orderlist[i].type == 1) {
            const goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: orderlist[i].typeid, shopid: shopid}).find();
            goods.nums -= Number(orderlist[i].num);
            goodsdata.push(goods);
            goodsdatalog.push({
              departmentid: shopid,
              goodsid: orderlist[i].typeid,
              ordertype: 'KKD',
              orderid: orderid,
              nums: -1 * orderlist[i].num,
              addtime: order.addtime,
              posttime: addtime
            });
            if (orderlist[i].istemp == 1) {
              zancundata.push({
                guestid: order.guestid,
                goodsid: orderlist[i].typeid,
                price: orderlist[i].price,
                num: orderlist[i].num,
                nownum: orderlist[i].num,
                disprice: orderlist[i].price * orderlist[i].discount,
                amount: orderlist[i].amount,
                orderid: orderid,
                shopid: this.shop_userinfo.departmentid,
                addtime: addtime,
                isgift: orderlist[i].isgift,
                isdisabled: 0,
                brandid: orderlist[i].brandid
              });
            }
          }
        }

        if (cardsubjectdata.length > 0) {
          rescardsubject = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(cardsubjectdata);
        }

        if (goodsdata.length > 0) {
          resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata);
          resgoodslog = await this.model('or_shop_goodslog').db(model.db()).addMany(goodsdatalog);
        }

        if (zancundata.length > 0) {
          reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(zancundata);
        }

        // 开始处理银行信息
        // 查看是否有余额和赠送余额消费
        const guestaccount = {arrivetime: addtime};
        let resguestaccountlog = 1;
        if (data.order.usebalance > 0 || data.order.usegiftbalance > 0) {
          const guest = await this.model('or_guest').db(model.db()).where({id: order.guestid}).find();
          if (guest.giftbalance - data.order.usegiftbalance < 0) {
            await model.rollback();
            return this.fail('该客户赠送余额不足以支付当前订单！');
          }

          guestaccount.balance = guest.balance - data.order.usebalance;
          guestaccount.giftbalance = guest.giftbalance - data.order.usegiftbalance;

          resguestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).add({
            guestid: order.guestid,
            shopid: shopid,
            ordertype: 'KKD',
            orderid: orderid,
            balance: -1 * data.order.usebalance,
            giftbalance: -1 * data.order.usegiftbalance,
            addtime: addtime,
            type: 3
          });
        }

        const resguestaccount = await this.model('or_guest').db(model.db()).where({id: order.guestid}).update(guestaccount);

        // 处理账户余额
        let resaccount = 1, resaccountlog = 1;
        if (data.paylist.length > 0) {
          let accountdata = [], accountdatalog = [];
          for (var i = data.paylist.length - 1; i >= 0; i--) {
            const account = await this.model('or_shop_account').db(model.db()).where({id: data.paylist[i].accountid}).find();
            account.balance += Number(data.paylist[i].paymoney);
            accountdata.push(account);
            accountdatalog.push({
              departmentid: shopid,
              accountid: data.paylist[i].accountid,
              ordertype: 'KKD',
              type: 1,
              orderid: orderid,
              money: data.paylist[i].paymoney,
              addtime: addtime
            });
          }
          resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountdata);
          resaccountlog = await this.model('or_shop_accountlog').db(model.db()).addMany(accountdatalog);
        }

        let resxianjin = 1, resreduce = 1, resyeji = 1;
        // 现金业绩表
        // 重新规划业绩分配，暂时用两种方式
        if (data.yejilist.length > 0) {
          let yejidata = [], selluserList = [], reduceuserList = [];
          data.yejilist.forEach((row) => {
            yejidata.push({
              shopid: shopid,
              orderid: data.order.id,
              ordertype: 'KKD',
              xianjinyeji: row.xianjinyeji,
              kahaoyeji: row.kahaoyeji,
              userid: row.userid,
              bumenid: row.bumenid,
              xiaozuid: row.xiaozuid,
              guestid: data.order.guestid,
              fuwutype: row.fuwutype,
              addtime: addtime
            });
            if (row.xianjinyeji > 0) {
              selluserList.push({
                orderid: data.order.id,
                feattype: 'KKD',
                shopid: shopid,
                feat: row.xianjinyeji,
                userid: row.userid,
                bumenid: row.bumenid,
                xiaozuid: row.xiaozuid,
                guestid: data.order.guestid,
                addtime: addtime
              });
            }
            if (row.kahaoyeji > 0) {
              reduceuserList.push({
                orderid: data.order.id,
                feattype: 'KKD',
                shopid: shopid,
                feat: row.kahaoyeji,
                userid: row.userid,
                bumenid: row.bumenid,
                xiaozuid: row.xiaozuid,
                guestid: data.order.guestid,
                addtime: addtime
              });
            }
          });

          if (selluserList.length > 0) {
            resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
          }
          if (reduceuserList.length > 0) {
            resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
          }
          resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata);
        }

        if (resreduce && resyeji && resxianjin && resorder && resguestaccount && resguestaccountlog && resaccount && resaccountlog && resgoods && resgoodslog && reszancun && rescardsubject) {
          await model.commit();
          return this.success('结账成功');
        } else {
          await model.rollback();
          return this.fail('结账失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('结账失败');
      }
    });
  }

  // 编辑开卡订单操作
  async editopencardAction() {
    const data = JSON.parse(this.post('data'));
    const addtime = Math.round(new Date().valueOf() / 1000);
    const shopid = this.shop_userinfo.departmentid;
    let order = data.order, cards = data.cards;

    const isstatus = await this.model('or_shop_order').where({id: order.id, status: 0}).find();
    if (think.isEmpty(isstatus)) {
      return this.fail('当前订单已结账！');
    }

    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        const datas = {
          guestid: data.ginfo.id,
          recemoney: data.order.usemoney,
          cardreduce: 0,
          usebalance: data.order.usebalance,
          usegiftbalance: data.order.usegiftbalance,
          operatorid: this.shop_userinfo.id,
          remarks: order.remarks,
          iscross: data.order.crossShop
        };
        const resorder = await model.where({id: order.id}).update(datas);
        if (!resorder) {
          await model.rollback();
          return this.fail('更新订单失败');
        }
        // 刪除以前的
        const resdel = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: order.id}).delete();

        const addorderinfo = [];
        for (var i = 0, cardlen = cards.length; i < cardlen; i++) {
          addorderinfo.push({
            departmentid: shopid,
            orderid: order.id,
            consumetype: 1,
            type: cards[i].rowtype,
            typeid: cards[i].id,
            typename: cards[i].name,
            num: cards[i].num,
            price: cards[i].price,
            totalprice: cards[i].num * cards[i].price,
            discount: cards[i].discount,
            amount: cards[i].amount,
            usemoney: cards[i].usemoney,
            usebalance: cards[i].usebalance,
            usegiftbalance: cards[i].usegiftbalance,
            usecard: 0,
            isgift: cards[i].isgift ? 1 : 0,
            istemp: cards[i].rowtype == 1 ? 1 : 0,
            brandid: cards[i].brandid ? cards[i].brandid : 0,
            cost: cards[i].cost
          });
        }
        // 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
        const resguest = await this.model('or_guest').db(model.db()).where({id: data.ginfo.id}).update({remarks: data.ginfo.remarks});

        const resadd = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorderinfo);

        if (resdel && resadd) {
          await model.commit();
          return this.success({info: '更改成功', id: order.id});
        } else {
          await model.rollback();
          return this.fail('更改成功');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('编辑失败');
      }
    });
  }

  // 删除开卡单
  async deleteopencardeAction() {
    const orderid = this.post('id');

    /*
		 * 删除操作
		 * 首先要判断当前订单是否结账，是否存在
		 * 根据orderid把or_shop_order表里订单删除
		 * 然后把or_shop_orderinfo表里对于的信息也删除
		 */

    const oinfo = await this.model('or_shop_order').where({id: orderid}).find();

    if (think.isEmpty(oinfo)) {
      return this.fail('当前订单不存在！');
    }
    if (oinfo.status) {
      return this.fail('当前订单已结账！');
    }

    // 删除操作开始
    const model = this.model('or_shop_order');
    // 方式一
    await model.transaction(async() => {
      try {
        const delorder = await model.where({id: orderid}).delete();
        const delinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: orderid}).delete();
        if (delorder && delinfo) {
          await model.commit();
          return this.success('删除成功');
        } else {
          await model.rollback();
          return this.fail('删除失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('删除失败！');
      }
    });
  }

  // 订单信息显示和审核页面
  async cardinfoAction() {
    if (this.isGet) {
      const id = this.get('orderid');
      // 获取订单信息
      const oinfo = await this.model('or_shop_order').where({id: id}).find();
      // 获取订单的客户信息
      const ginfo = await this.model('or_guest').where({id: oinfo.guestid}).find();
      // 获取当前订单绩效分配的员工
      const uinfo = await this.model('or_shop_yejixianjin')
        .alias('yj')
        .field('yj.userid, yj.feat, u.name, u.username, u.zhichengid, p.name as zhicheng')
        .join('`think_or_app_user` u on u.id = yj.userid')
        .join('`think_or_position` p on p.id = u.zhichengid')
        .where({'yj.orderid': id})
        .select();
      // 获取订单分表数据
      const olist = await this.model('or_shop_orderinfo')
        .alias('i')
        .field('c.id,c.name,i.price,i.amount,i.discount,c.validity,c.typeid')
        .join('think_or_card c on i.typeid = c.id')
        .where({orderid: id}).select();
      // 获取收款金额及收款日志
      const alist = await this.model('or_shop_accountlog')
        .alias('l')
        .field('a.id,a.name,a.accounttype,a.accountsn,l.money as paymoney')
        .join('think_or_shop_account a on l.accountid = a.id')
        .where({orderid: id}).select();

      const data = {
        order: oinfo,
        guestinfo: ginfo,
        usersinfo: uinfo,
        orderinfo: olist,
        accountinfo: alist
      };

      return this.json(data);
    } else {
      // 开卡订单审核
      const id = this.post('id');
      const whetherSH = await this.model('or_shop_order').where({id: id}).find();
      /* if (whetherSH.status == 2) {
				return this.fail('该订单已审核');
			} */
      const res = await this.model('or_shop_order').where({id: id}).update({'status': 2, 'auditorid': this.shop_userinfo.id});
      return res ? this.success({info: '审核成功！'}) : this.fail('审核失败！');
    }
  }

  // 启用或禁用卡
  async unstopAction() {
    const id = this.get('id');
    const zt = this.get('zt');

    const res = await this.model('or_shop_card').where({id: id}).update({isdisabled: zt});

    if (zt == 0) {
      return res ? this.success('启用成功') : this.fail('启用失败');
    } else {
      return res ? this.success('禁用成功') : this.fail('禁用失败');
    }
  }

  // 获取店家信息
  async getshopinfoAction() {
    const sinfo = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).find();
    return this.json(sinfo);
  }

  // 拉取编辑信息
  async geteditinfoAction() {
    const id = this.get('id');
    const order = await this.model('or_shop_order').where({id: id}).find();
    const ginfo = await this.model('or_guest').where({id: order.guestid}).field('id,name,phone').find();
    const cinfo = await this.model('or_shop_orderinfo')
      .alias('o')
      .join('`think_or_shop_guestcard` c on c.id = o.guestcardid')
      .where({'o.orderid': id})
      .select();
    const ainfo = await this.model('or_shop_accountlog')
      .alias('l')
      .field('l.accountid, l.money, a.name, a.accountsn, a.accounttype')
      .join('`think_or_shop_account` a on a.id = l.accountid')
      .where({'l.orderid': id})
      .select();
    const uinfo = await this.model('or_shop_yejixianjin')
      .alias('xj')
      .field('xj.feat, u.name, u.username, p.name as zhicheng')
      .join('`think_or_app_user` u on u.id = xj.userid')
      .join('`think_or_position` p on p.id = u.zhichengid')
      .where({'xj.orderid': id})
      .select();
    const data = {
      oinfo: order,
      ginfo: ginfo,
      cinfo: cinfo,
      ainfo: ainfo,
      uinfo: uinfo
    };
    return this.json(data);
  }

  // 开卡反结账（必须为已结账未审核状态）
  async unpayAction() {
    const id = this.post('id');
    const shopid = this.shop_userinfo.departmentid;

    // 判斷是否可操作
    const order = await this.model('or_shop_order').where({id: id}).find();

    if (order.status != 1) {
      return this.fail('当前订单未结账或已审核');
    }

    const subjectlist = await this.model('or_shop_guestcardsubject').where({orderid: id}).select();
    const goodslist = await this.model('or_shop_guest_temp_reserve').where({orderid: id}).select();

    if (subjectlist.length > 0) {
      for (var i = subjectlist.length - 1; i >= 0; i--) {
        if (subjectlist[i].num - subjectlist[i].nownum > 0) {
          return this.fail('该订单开出的卡项已经被使用，不能反结账！');
        }
      }
    }
    if (goodslist.length > 0) {
      for (var i = goodslist.length - 1; i >= 0; i--) {
        if (goodslist[i].num - goodslist[i].nownum > 0) {
          return this.fail('该订单暂存的商品已被领走，不能反结账！');
        }
      }
    }

    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        // 更改订单状态
        const resorder = await model.where({id: id}).update({
          auditorid: 0,
          status: 0
        });

        // 商品数量和库存日志
        const goodslog = await this.model('or_shop_goodslog').db(model.db()).where({ordertype: 'KKD', orderid: id}).select();
        let resgoods = 1, resgoodslog = 1, goodsdata = [];
        if (goodslog.length > 0) {
          for (var i = goodslog.length - 1; i >= 0; i--) {
            const goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: goodslog[i].goodsid, shopid: shopid}).find();
            goods.nums -= Number(goodslog[i].nums);
            goodsdata.push(goods);
          }
          resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata);
          resgoodslog = await this.model('or_shop_goodslog').db(model.db()).where({ordertype: 'KKD', orderid: id}).delete();
        }

        // 删除暂存商品
        const reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).where({orderid: id, shopid: shopid}).delete();

        // 删除客户卡项表
        const resguestsubject = await this.model('or_shop_guestcardsubject').db(model.db()).where({orderid: id}).delete();

        // 如果有普通收款，删除日志，返还金额
        let resaccount = 1, resaccountlog = 1;
        if (order.recemoney > 0) {
          const accountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'KKD', orderid: id}).select();
          const accountdata = [];
          for (var i = accountlog.length - 1; i >= 0; i--) {
            const account = await this.model('or_shop_account').db(model.db()).where({id: accountlog[i].accountid}).find();
            account.balance -= Number(accountlog[i].money);
            accountdata.push(account);
          }
          resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountdata);
          resaccountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'KKD', orderid: id}).delete();
        }

        // 如果有余额或赠送余额支出
        let resdelbalancelog = 1, resbalance = 1;
        // 判断是否使用余额
        if (order.usebalance != 0 || order.usegiftbalance != 0) {
          // 删除日志，返回金额
          resdelbalancelog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'KKD', orderid: id}).delete();
          // 取金额
          const ginfo = await this.model('or_guest').db(model.db()).where({id: order.guestid}).find();
          resbalance = await this.model('or_guest').db(model.db()).where({id: order.guestid}).update({
            balance: ginfo.balance + Number(order.usebalance),
            giftbalance: ginfo.giftbalance + Number(order.usegiftbalance)
          });
        }

        // 删除业绩
        const resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: id, feattype: 'KKD'}).delete();

        const resyejiticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: id, ordertype: 'KKD'}).delete();

        if (resyejiticheng !== false && resxianjin !== false && resorder && resdelbalancelog && resbalance && resaccount && resaccountlog && resgoods && resgoodslog && resguestsubject !== false && reszancun !== false) {
          await model.commit();
          return this.success('反结账成功');
        } else {
          await model.rollback();
          return this.fail('反结账失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('反结账失败');
      }
    });
  }

  // 重新分配订单业绩（已结账）现金业绩
  async resertallotAction() {
    const data = JSON.parse(this.post('data'));
    const nowtime = Math.round(Date.parse(new Date()) / 1000);
    // 获取订单实时信息判断状态
    const order = await this.model('or_shop_order').where({id: data.order.id}).find();

    // 如果状态为3则不能更改业绩
    if (order.status == 2) {
      return this.fail('该订单已经审核不能再分配业绩！');
    }
    if (order.status == 0) {
      return this.fail('该订单尚未结账，不能分配业绩！');
    }
    // 删除已经分配好的业绩重新分配
    const model = this.model('or_shop_yejixianjin');
    await model.transaction(async() => {
      try {
        let resyeji = 1, resxianjin = 1, resreduce = 1, resdelxianjin = 1, resdelreduce = 1, resdelyeji = 1;

        resdelxianjin = await model.where({orderid: data.order.id, feattype: 'KKD'}).delete();
        resdelreduce = await this.model('or_shop_yejicardreduce').db(model.db()).where({orderid: data.order.id, feattype: 'KKD'}).delete();
        resdelyeji = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: data.order.id, ordertype: 'KKD'}).delete();

        if (data.yejilist.length > 0) {
          let yejidata = [], selluserList = [], reduceuserList = [];
          data.yejilist.forEach((row) => {
            yejidata.push({
              shopid: this.shop_userinfo.departmentid,
              orderid: data.order.id,
              ordertype: 'KKD',
              xianjinyeji: row.xianjinyeji,
              kahaoyeji: row.kahaoyeji,
              userid: row.userid,
              bumenid: row.bumenid,
              xiaozuid: row.xiaozuid,
              guestid: data.order.guestid,
              fuwutype: row.fuwutype,
              addtime: data.order.addtime
            });
            if (row.xianjinyeji > 0) {
              selluserList.push({
                orderid: data.order.id,
                feattype: 'KKD',
                shopid: this.shop_userinfo.departmentid,
                feat: row.xianjinyeji,
                userid: row.userid,
                bumenid: row.bumenid,
                xiaozuid: row.xiaozuid,
                guestid: data.order.guestid,
                addtime: data.order.addtime
              });
            }
            if (row.kahaoyeji > 0) {
              reduceuserList.push({
                orderid: data.order.id,
                feattype: 'KKD',
                shopid: this.shop_userinfo.departmentid,
                feat: row.kahaoyeji,
                userid: row.userid,
                bumenid: row.bumenid,
                xiaozuid: row.xiaozuid,
                guestid: data.order.guestid,
                addtime: data.order.addtime
              });
            }
          });

          if (selluserList.length > 0) {
            resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
          }
          if (reduceuserList.length > 0) {
            resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
          }
          resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata);
        }

        if (resyeji && resxianjin && resreduce && resdelxianjin !== false && resdelreduce !== false && resdelyeji) {
          await model.commit();
          return this.success({data: 200, info: '编辑成功'});
        } else {
          await model.rollback();
          return this.fail('编辑失败！');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('编辑失败！');
      }
    });
  }

  // 获取分店未停用项目接口
  async getshopsubjectAction() {
    const shopid = this.shop_userinfo.departmentid;

    const list = await this.model('or_shop_subject')
      .alias('ss')
      .field('ss.subjectid, s.id, s.name, ss.price, s.number')
      .join('`think_or_subject` s on s.id=ss.subjectid')
      .where({'ss.shopid': shopid, 'ss.isdisable': 0})
      .select();

    return this.json(list);
  }

  // shop created customs of cards
  async createcardAction() {
    const data = JSON.parse(this.post('data'));
    const category = this.post('type');

    const shopid = this.shop_userinfo.departmentid;
    const time = Math.round(new Date().valueOf() / 1000);

    // check number or name is repeat.
    const isrepeat = await this.model('or_shop_card').where('shopid=' + shopid + ' AND (number="' + data.number + '" OR name="' + data.name + '")').select();

    if (!think.isEmpty(isrepeat)) {
      return this.fail('卡项编号或名称重复');
    }

    const model = this.model('or_shop_card');
    await model.transaction(async() => {
      try {
        const cardleng = await model.where({shopid: shopid}).count('id');

        const addone = {
          no: cardleng + 1,
          name: data.name,
          number: data.number,
          price: data.price,
          category: category,
          remarks: data.remarks,
          addtime: time,
          shopid: shopid,
          tdtype: data.tdtype
        };

        if (data.tdtype == 1) addone.percent = Number(data.percent / 100).toFixed(4);
        else addone.fixed = data.fixed;

        let cardid = 0, tjkx = 0;

        if (category == 1) {
          addone.validity = data.validity;

          cardid = await model.add(addone);

          const addtwo = [];

          data.slist.forEach((v) => {
            addtwo.push({
              cardid: cardid,
              subjectid: v.subjectid,
              // subjectnumber: v.number,
              price: v.price,
              amount: v.amount,
              xhprice: v.xhprice * 1
            });
          });

          tjkx = await this.model('or_shop_cardsubject').db(model.db()).addMany(addtwo);
        } else {
          cardid = await model.add(addone);

          const addthree = [];

          data.slist.forEach((v) => {
            addthree.push({
              cardid: cardid,
              subjectid: v.subjectid,
              // subjectnumber: v.number,
              price: v.price,
              disprice: v.disprice,
              num: v.num
            });
          });

          tjkx = await this.model('or_shop_cardsubject').db(model.db()).addMany(addthree);
        }
        if (cardid && tjkx) {
          await model.commit();
          return this.success('创建成功');
        } else {
          await model.rollback();
          return this.fail('创建失败');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('创建失败');
      }
    });
  }

  // look shop card infomation
  async lookcardinfoAction() {
    const id = this.get('id');

    const info = await this.model('or_shop_card').where({id: id}).find();

    const list = await this.model('or_shop_cardsubject')
      .alias('cs')
      .field('cs.*, s.name, s.number')
      .join('`think_or_subject` s on s.id=cs.subjectid')
      .where({'cs.cardid': id})
      .select();

    const data = {
      info: info,
      list: list
    };

    return this.json(data);
  }

  // edit shop card infomation
  async editcardAction() {
    const data = JSON.parse(this.post('data'));
    const dels = JSON.parse(this.post('dels'));
    const category = this.post('type');

    const shopid = this.shop_userinfo.departmentid;

    const isrepeat = await this.model('or_shop_card').where('shopid="' + shopid + '" AND (number="' + data.number + '" OR name="' + data.name + '") AND id!=' + data.id).find();

    if (!think.isEmpty(isrepeat)) {
      return this.fail('更改的卡名称或编号重复');
    }

    const model = this.model('or_shop_card');

    await model.transaction(async() => {
      try {
        if (dels.length) {
          const del_res = await this.model('or_shop_cardsubject').db(model.db()).where({id: ['IN', dels]}).delete();
          if (!del_res) {
            await model.rollback();
            return this.fail('删除项目失败');
          }
        }

        const updatecard = {
          name: data.name,
          number: data.number,
          price: data.price,
          remarks: data.remarks,
          validity: data.validity,
          tdtype: data.tdtype
        };

        if (data.tdtype == 1) {
          updatecard.percent = Number(data.percent / 100).toFixed(4);
          updatecard.fixed = 0;
        } else {
          updatecard.percent = 0;
          updatecard.fixed = data.fixed;
        }

        const upcard_res = await model.where({id: data.id}).update(updatecard);
        const add_kx = [];
        for (var i = data.slist.length - 1; i >= 0; i--) {
          if (data.slist[i].id) {
            const gg_res = await this.model('or_shop_cardsubject').db(model.db()).where({id: data.slist[i].id}).update({
              'price': data.slist[i].price,
              'disprice': data.slist[i].disprice,
              'num': data.slist[i].num,
              'amount': data.slist[i].amount,
              'xhprice': data.slist[i].xhprice * 1
            });

            if (!gg_res) {
              await model.rollback();
              return this.fail('更新卡项失败');
            }
          } else {
            add_kx.push({
              cardid: data.id,
              subjectid: data.slist[i].subjectid,
              subjectnumber: data.slist[i].number,
              price: data.slist[i].price,
              disprice: data.slist[i].disprice,
              num: data.slist[i].num,
              amount: data.slist[i].amount,
              xhprice: data.slist[i].xhprice * 1
            });
          }
        }

        if (add_kx.length) {
          const addkx_res = await this.model('or_shop_cardsubject').db(model.db()).addMany(add_kx);
          if (!addkx_res) {
            await model.rollback();
            return this.fail('添加卡项失败');
          }
        }

        await model.commit();
        return this.success('更改卡项成功');
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('更改失败');
      }
    });
  }
  // 获取分配的业绩
  async getorderfenpeilistAction() {
    const id = this.get('id');
    const yejilist = await this.model('or_shop_yejiticheng')
      .alias('y')
      .field('y.*,u.name')
      .join('left join `think_or_app_user` u on y.userid = u.id')
      .where({'y.ordertype': 'KKD', 'y.orderid': id})
      .select();
    return this.json(yejilist);
  }

  // 计算订单的现金提成，卡耗提成，手工提成
  async getjisuantichengAction() {
    const id = this.post('id');
    // 列出订单信息
    const orderlist = await this.model('or_shop_orderinfo').where({orderid: id}).select();
    let ax = 0, ak = 0; // 总现金业绩，总卡耗业绩
    let xt = 0, kt = 0, st = 0; // 总现金卡耗手工提成
    // 获取开卡的提点
    const baseConfig = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find();
    const openCardTidian = baseConfig.kaikapercent;
    for (var i = orderlist.length - 1; i >= 0; i--) {
      let x = 0, k = 0;
      if (orderlist[i].consumetype == 1) {
        // 普通的产品消费
        x = orderlist[i].usemoney;
        k = orderlist[i].usebalance + Number(orderlist[i].usegiftbalance);
        /* if (orderlist[i].type == 1) {
					// 取商品
					let goods = await this.model('or_shop_goods')
					.where({goodsid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid})
					.find()
					// 取现金业绩和卡耗业绩
					orderlist[i].xianjinticheng = goods.tdtype == 1 ? x * goods.percent : x / (x + k) * orderlist[i].num * goods.fixed
					orderlist[i].kahaoticheng = goods.khtdtype == 1 ? k * goods.khpercent : k / (x + k) * orderlist[i].num * goods.khfixed
				}
				if (orderlist[i].type == 2) {
					let subject = await this.model('or_shop_subject').where({subjectid: orderlist[i].typeid, shopid: this.shop_userinfo.departmentid}).find()
					orderlist[i].xianjinticheng = subject.xstdtype == 1 ? x * subject.xspercent : x / (x + k) * orderlist[i].num * subject.xsfixed
					orderlist[i].kahaoticheng = 0
					orderlist[i].shougongticheng = 0
				}

				if (orderlist[i].type == 3) {
					let card = await this.model('or_shop_card').where({id: orderlist[i].typeid}).find()
					orderlist[i].xianjinticheng = card.tdtype == 1 ? x * card.percent : x / (x + k) * orderlist[i].num * card.fixed
				} */
        console.log(orderlist[i]);
        orderlist[i].xianjinticheng = x * openCardTidian;
        if (orderlist[i].cardtype == 1 && k > 0) {
          orderlist[i].kahaoticheng = k * openCardTidian;
        }
      }

      orderlist[i].xianjinticheng = orderlist[i].xianjinticheng ? orderlist[i].xianjinticheng.toFixed(2) : 0;
      orderlist[i].kahaoticheng = orderlist[i].kahaoticheng ? orderlist[i].kahaoticheng.toFixed(2) : 0;
      orderlist[i].shougongticheng = 0;
      ax += Number(x);
      ak += Number(k);

      xt += Number(orderlist[i].xianjinticheng);
      kt += Number(orderlist[i].kahaoticheng);
      st += Number(orderlist[i].shougongticheng);
    }
    const fenpeilist = await this.model('or_shop_yejiticheng')
      .alias('y')
      .field('y.*, u.name')
      .join('left join `think_or_app_user` u on y.userid = u.id')
      .where({'y.ordertype': 'KKD', 'y.orderid': id})
      .select();

    // 查询是否开通了阶梯提成
    const order = await this.model('or_shop_order').where({id: id}).find();

    const dates = new Date(order.addtime * 1000);
    const beginToday = dates.setHours(0, 0, 0, 0) / 1000;
    const beginMonth = new Date(dates.getFullYear(), dates.getMonth()).getTime() / 1000;
    const beginYear = new Date(dates.getFullYear(), 0).getTime() / 1000;

    if (fenpeilist.length > 0 && order.status != 2) {
      for (var i = fenpeilist.length - 1; i >= 0; i--) {
        const xianjin = (fenpeilist[i].xianjinyeji / ax) * xt ? ((fenpeilist[i].xianjinyeji / ax) * xt).toFixed(2) : 0;
        const kahao = (fenpeilist[i].kahaoyeji / ak) * kt ? ((fenpeilist[i].kahaoyeji / ak) * kt).toFixed(2) : 0;
        fenpeilist[i].xianjinticheng = xianjin || 0;
        fenpeilist[i].kahaoticheng = kahao || 0;
        fenpeilist[i].xianjinjieti = 0;
        fenpeilist[i].xianjinxinxi = [];
        fenpeilist[i].kahaojieti = 0;
        fenpeilist[i].kahaoxinxi = [];
        if (baseConfig && baseConfig.isticheng) {
          // 取本月开始时间戳
          fenpeilist[i].userfeat = await this.model('or_shop_yejiticheng').field('sum(if(addtime > ' + beginToday + ', xianjinyeji, 0)) as todayxj, sum(if(addtime > ' + beginToday + ', kahaoyeji, 0)) as todaykh, sum(if(addtime > ' + beginMonth + ', xianjinyeji, 0)) as monthxj, sum(if(addtime > ' + beginMonth + ', kahaoyeji, 0)) as monthkh,sum(if(addtime > ' + beginYear + ', xianjinyeji, 0)) as yearxj, sum(if(addtime > ' + beginYear + ', kahaoyeji, 0)) as yearkh').where({userid: fenpeilist[i].userid, addtime: {'>=': beginYear, '<=': fenpeilist[i].addtime}}).find();
          // 取出配置
          const cf = JSON.parse(baseConfig.tichengarr || '[]');
          if (cf.length) {
            for (let m = 0; m < cf.length; m++) {
              switch (cf[m].timetype) {
                case 1:
                  if (cf[m].feattype == 1) {
                    if (cf[m].feet <= fenpeilist[i].userfeat.yearxj) {
                      // console.log(1)
                      fenpeilist[i].xianjinjieti += fenpeilist[i].xianjinyeji * cf[m].percent / 100;
                      fenpeilist[i].xianjinxinxi.push(fenpeilist[i].name + '年度现金业绩为' + fenpeilist[i].userfeat.yearxj + '元，获得年度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
                  } else {
                    if (cf[m].feet <= fenpeilist[i].userfeat.yearkh) {
                      // console.log(1)
                      fenpeilist[i].kahaojieti += fenpeilist[i].kahaoyeji * cf[m].percent / 100;
                      fenpeilist[i].kahaoxinxi.push(fenpeilist[i].name + '年度卡耗业绩为' + fenpeilist[i].userfeat.yearkh + '元，获得年度卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
                  }

                  break;
                case 2:
                  if (cf[m].feattype == 1) {
                    if (cf[m].feet <= fenpeilist[i].userfeat.monthxj) {
                      // console.log(2)
                      fenpeilist[i].xianjinjieti += fenpeilist[i].xianjinyeji * cf[m].percent / 100;
                      fenpeilist[i].xianjinxinxi.push(fenpeilist[i].name + '月度现金业绩为' + fenpeilist[i].userfeat.monthxj + '元，获得月度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
                  } else {
                    if (cf[m].feet <= fenpeilist[i].userfeat.monthkh) {
                      // console.log(2)
                      fenpeilist[i].kahaojieti += fenpeilist[i].kahaoyeji * cf[m].percent / 100;
                      fenpeilist[i].kahaoxinxi.push(fenpeilist[i].name + '月度卡耗业绩为' + fenpeilist[i].userfeat.monthkh + '元，获得月度卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
                  }

                  break;
                case 3:
								  	if (cf[m].feattype == 1) {
								  		if (cf[m].feet <= fenpeilist[i].userfeat.todayxj) {
                      // console.log(3)
                      fenpeilist[i].xianjinjieti += fenpeilist[i].xianjinyeji * cf[m].percent / 100;
                      fenpeilist[i].xianjinxinxi.push(fenpeilist[i].name + '当日现金业绩为' + fenpeilist[i].userfeat.todayxj + '元，获得当日现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
								  	} else {
								  		if (cf[m].feet <= fenpeilist[i].userfeat.todaykh) {
                      // console.log(3)
                      fenpeilist[i].kahaojieti += fenpeilist[i].kahaoyeji * cf[m].percent / 100;
                      fenpeilist[i].kahaoxinxi.push(fenpeilist[i].name + '当日卡耗业绩为' + fenpeilist[i].userfeat.todaykh + '元，获得当日卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + fenpeilist[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
								  	}
                  break;
              }
            }
          }
        }
        fenpeilist[i].xianjinjieti = fenpeilist[i].xianjinjieti.toFixed(2);
        fenpeilist[i].kahaojieti = fenpeilist[i].kahaojieti.toFixed(2);
      }
    }
    const data = {
      orderlist: orderlist,
      fenpeilist: fenpeilist
    };
    return this.json(data);
  }
}
